import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  cart: [],
};

const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    addItem(state, action) {
      console.log(action);
      state.cart.push(action.payload);
    },
    removeItem(state, action) {
      state.cart = state.cart.filter((item) => item.pizzaId !== action.payload);
    },
    clearCart(state) {
      state.cart = [];
    },
    increaseItemQuantity(state, action) {
      const pizza = state.cart.find((el) => el.pizzaId === action.payload);
      pizza.quantity += 1;
      pizza.totalPrice += pizza.price;
    },
    decreaseItemQuantity(state, action) {
      const pizza = state.cart.find((el) => el.pizzaId === action.payload);
      pizza.quantity -= 1;
      pizza.totalPrice -= pizza.price;
    },
  },
});

export const {
  addItem,
  removeItem,
  clearCart,
  increaseItemQuantity,
  decreaseItemQuantity,
} = cartSlice.actions;

export default cartSlice.reducer;

export const totalQuantity = (state) =>
  state.cart.cart.reduce((acc, el) => acc + el.quantity, 0);
export const totalPrice = (state) =>
  state.cart.cart.reduce((acc, el) => acc + el.totalPrice, 0);
